In this article, we’ll see how to replace word document placeholder using Docxtemplater & pizzip library with Node js Project.
Word Document Placeholder
What is Docxtemplater?
Docxtemplater is a programmatically used mail merging tool that handles conditions, loops, and that can be extended to insert anything (tables, html, images).
Docxtemplater uses JSON (Javascript objects) as data input so it is easy to use from other languages as well. It manages templates in docx but also in pptx.
It functions similarly to a templating engine.
Many solutions such as docx.js, docx4j, python-docx can generate docx, but they allow you to write specific code in order to create a title, an image, …
In addition, docxtemplater is based on tag concepts, and each form of tag exposes the user to write the template.
What is pizzip?
PizZip is a fork of JSZip version 2.x, because we want a synchronous Zip library.
A library for creating, reading and editing .zip files with Javascript, with a lovely and simple API.
Create Node js Project
Let’s initialize the project for word document placeholder replacement with npm init –yes command.
2 3 4 5 6 |
$ mkdir node-demo $ cd node-demo $ npm init --yes |
Install the Docxtemplater & pizzip
Now install the Docxtemplater the module as shown below:
2 3 4 |
$ npm install docxtemplater pizzip |
Create an app.js file
Now create a file called app.js
and place the following code.
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 |
var PizZip = require('pizzip'); var Docxtemplater = require('docxtemplater'); var fs = require('fs'); var path = require('path'); // The error object contains additional information when logged with JSON.stringify (it contains a properties object containing all suberrors). function replaceErrors(key, value) { if (value instanceof Error) { return Object.getOwnPropertyNames(value).reduce(function(error, key) { error[key] = value[key]; return error; }, {}); } return value; } function errorHandler(error) { console.log(JSON.stringify({error: error}, replaceErrors)); if (error.properties && error.properties.errors instanceof Array) { const errorMessages = error.properties.errors.map(function (error) { return error.properties.explanation; }).join("\n"); console.log('errorMessages', errorMessages); // errorMessages is a humanly readable message looking like this : // 'The tag beginning with "foobar" is unopened' } throw error; } //Load the docx file as a binary var content = fs .readFileSync(path.resolve(__dirname, 'input.docx'), 'binary'); var zip = new PizZip(content); var doc; try { doc = new Docxtemplater(zip); } catch(error) { // Catch compilation errors (errors caused by the compilation of the template : misplaced tags) errorHandler(error); } //set the templateVariables doc.setData({ first_name: 'Tutorials', last_name: 'Website', phone: '0652455478', description: 'Tutorials Website Article' }); try { // render the document (replace all occurences of {first_name} by John, {last_name} by Doe, ...) doc.render() } catch (error) { // Catch rendering errors (errors relating to the rendering of the template : angularParser throws an error) errorHandler(error); } var buf = doc.getZip() .generate({type: 'nodebuffer'}); // buf is a nodejs buffer, you can either write it to a file or do anything else with it. fs.writeFileSync(path.resolve(__dirname, 'output.docx'), buf); |
You can download input.docx and put it in the same folder than your JS file.
Execute app.js Code
Now execute the code with node app.js
command, it will generate a new word document called output.docx
in the project folder.
2 3 4 |
node app.js |
Also Read: File Upload in Node js using Multer
Conclusion:
I hope you found this tutorial helpful for your project. Replace Word Document Placeholder with Node js is an important feature for any web application. So here we are, completed the basic concept using Docxtemplater & pizzip in node.js and express.js
Are you want to get implementation help, or modify or extend the functionality of this script? Submit paid service request
Pradeep Maurya is the Professional Web Developer & Designer and the Founder of “Tutorials website”. He lives in Delhi and loves to be a self-dependent person. As an owner, he is trying his best to improve this platform day by day. His passion, dedication and quick decision making ability to stand apart from others. He’s an avid blogger and writes on the publications like Dzone, e27.co